package com.tebiecloud.order.server.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.beust.jcommander.internal.Maps;
import com.tebiecloud.base.client.model.entity.BaseUser;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.DateUtils;
import com.tebiecloud.common.utils.JsonUtils;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUser;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserExpand;
import com.tebiecloud.mpweixin.client.model.vo.PlusUserAmountVo;
import com.tebiecloud.order.client.model.entity.*;
import com.tebiecloud.order.server.service.*;
import com.tebiecloud.order.server.service.feign.*;
import com.tebiecloud.retail.client.constants.RetailConstants;
import com.tebiecloud.retail.client.model.entity.RetailOrder;
import com.tebiecloud.store.client.model.entity.Store;
import com.tebiecloud.store.client.model.entity.StoreStaff;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 支付回调接口
 */
@Slf4j
@RestController
@RequestMapping(value = "/ordercallback")
public class OrderCallbackController {

    @Autowired
    YunStPaymentServiceClient yunStPaymentServiceClient;

    @Autowired
    OrderrService orderrService;

    @Autowired
    OrderStats1Service orderStats1Service;

    @Autowired
    OrderGoodsService orderGoodsService;

    @Autowired
    RetailOrderServiceClient retailOrderServiceClient;

    @Autowired
    GoodsSpecificationServiceClient goodsSpecificationServiceClient;

    @Autowired
    ActGoodsRefServiceClient actGoodsRefServiceClient;

    @Autowired
    MpweixinServiceClient mpweixinServiceClient;

    @Autowired
    BaseUserServiceClient baseUserServiceClient;

    @Autowired
    OrderWriteOffLogService orderWriteOffLogService;

    @Autowired
    private OrderStats2Service orderStats2Service;

    @Autowired
    private StoreFlowServiceClient storeFlowServiceClient;

    @Autowired
    private StoreServiceClient storeServiceClient;

    @Autowired
    private ReserveOrderService reserveOrderService;

    @Autowired
    private ReserveService reserveService;

    @Autowired
    private StoreStaffServiceClient storeStaffServiceClient;

    /**
     * 支付回调
     * @param rps
     * @param orderId 订单号
     * @param userId 下单人
     * @return
     */
    @RequestMapping("consumeApplyCallBack")
    public ResultBody consumeApplyCallBack(
            @RequestParam(value = "rps") String rps,
            @RequestParam(value = "orderId") long orderId,
            @RequestParam(value = "userId") long userId){
        log.info(">>minjie  进入支付回调---- rps:{}",rps);
        JSONObject requset = JSON.parseObject(rps);
        JSONObject returnValue = requset.getJSONObject("returnValue");
        String status =  requset.getString("status");
        if(status.equals("OK")) {
            String openId = ""; //openid
            String unionid = ""; //unionid
            String nickname = ""; //昵称
            String headimgurl = ""; //头像
            String phone = ""; //手机号码
            //更新订单数据
            QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
            orderrQueryWrapper.eq("order_id",orderId);
            orderrQueryWrapper.eq("status",1);
            Orderr orderr = orderrService.getOne(orderrQueryWrapper);
            log.info(">> minjie 回调查询订单："+ JsonUtils.Obj2Str(orderr));
            if(orderr == null)return ResultBodyUtils.failed("订单查询失败！");
            //更新订单商品数据
            QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
            orderGoodsQueryWrapper.eq("order_id",orderId);
            orderGoodsQueryWrapper.eq("sold",0);
            List<OrderGoods> orderGoodsList = orderGoodsService.list(orderGoodsQueryWrapper);
            //查询是否是预约单
            ReserveOrder reserveOrder = getReserveOrder(orderId);
            int orderStatus = 2;//初始化订单状态
            if(orderGoodsList==null || reserveOrder!=null)orderStatus = 4;
            if(orderr!=null){
                if(orderr.getCashierId()!=null)orderStatus = 4;
                phone = orderr.getPhone();//获取订单的手机号
                UpdateWrapper<Orderr> orderrUpdateWrapper = new UpdateWrapper<>();
                orderrUpdateWrapper.eq("order_id",orderId);
                Orderr orderr1 = new Orderr();
                orderr1.setStatus(orderStatus);//已支付
                orderr1.setUserId(userId);//更改谁的订单
                orderr1.setShutTime(new Date());//支付时间
                if(orderStatus==4)orderr1.setWritOffTime(new Date());//已核销
                orderrService.update(orderr1,orderrUpdateWrapper);
            }
            //更新分销数据
            retailOrderServiceClient.updateRetailOrder(orderId, orderStatus);
            //查询会员信息
            ResultBody<BaseUser> baseUserResultBody = baseUserServiceClient.infoBaseUser(userId);
            if(baseUserResultBody!=null && baseUserResultBody.getCode() == ResultEnum.OK.getCode()){
                BaseUser baseUser = baseUserResultBody.getData();
                log.info(">>minjie 查询下单人信息baseUser："+JsonUtils.Obj2Str(baseUser));
                String[] userNames = baseUser.getUserName().split(":");
                if(userNames.length>=2){
                    openId = userNames[1];
                }
            }
            if(openId!=""){
                ResultBody<MpweixinUser> mpweixinUserResultBody = mpweixinServiceClient.selectMpUserInfo(openId);
                if(mpweixinUserResultBody != null && mpweixinUserResultBody.getCode() == ResultEnum.OK.getCode()){
                    MpweixinUser mpweixinUser = mpweixinUserResultBody.getData();
                    log.info(">>minjie 查询下单人信息mpweixinUser："+JsonUtils.Obj2Str(mpweixinUser));
                    if(mpweixinUser!=null){
                        unionid = mpweixinUser.getUnionid();
                    }
                }
            }
            //获取用户信息
            ResultBody<MpweixinUserExpand> mpweixinUserExpandResultBody = mpweixinServiceClient.selectUserInfo(userId,null);
            if(mpweixinUserExpandResultBody!=null && mpweixinUserExpandResultBody.getCode() == ResultEnum.OK.getCode()){
                MpweixinUserExpand mpweixinUserExpand = mpweixinUserExpandResultBody.getData();
                log.info(">>minjie 查询下单人信息mpweixinUserExpand："+JsonUtils.Obj2Str(mpweixinUserExpand));
                if(mpweixinUserExpand!=null){
                    nickname = mpweixinUserExpand.getNickname();
                    headimgurl = mpweixinUserExpand.getHeadimgurl();
                    if(orderr!=null){
                        UpdateWrapper<Orderr> orderrUpdateWrapper = new UpdateWrapper<>();
                        orderrUpdateWrapper.eq("order_id",orderId);
                        Orderr orderr1 = new Orderr();
                        orderr1.setReceiverHeadimgurl(headimgurl);
                        orderrService.update(orderr1,orderrUpdateWrapper);
                    }
                }
            }
            if(unionid!=""){
                log.info(">> minjie 订单状态：{}",orderStatus);
                if(orderStatus==4){//收银不需要统计待核销
                    //加入会员统计表
                    log.info(">>minjie 会员统计;unionid:{},userId:{},storeId:{},nickname:{},headimgurl:{},phone:{},Price:{}，waitAmpount:{}",
                            unionid,userId,orderr.getStoreId(),nickname,headimgurl,phone,orderr.getPrice(),0);
                    orderStats1Service.createOrUpdate(unionid,userId,orderr.getStoreId(),
                            nickname,headimgurl,phone,orderr.getPrice(),0);
                }else {
                    log.info(">>minjie 会员统计;unionid:{},userId:{},storeId:{},nickname:{},headimgurl:{},phone:{},Price:{}，waitAmpount:{}",
                            unionid,userId,orderr.getStoreId(),nickname,headimgurl,phone,orderr.getPrice(),orderr.getPrice());
                    orderStats1Service.createOrUpdate(unionid,userId,orderr.getStoreId(),
                            nickname,headimgurl,phone,orderr.getPrice(),orderr.getPrice());
                }
            }

            if(orderGoodsList!=null && orderGoodsList.size()>0){
                UpdateWrapper<OrderGoods> orderGoodsUpdateWrapper = new UpdateWrapper<>();
                orderGoodsUpdateWrapper.eq("order_id",orderId);
                OrderGoods orderGoods1 = new OrderGoods();
                orderGoods1.setSold(1);//已出售
                orderGoodsService.update(orderGoods1,orderGoodsUpdateWrapper);
                //查询核销人信息
                Map<String,Object> writeOffMap = getWriteInfomation(orderr,reserveOrder);
                Long writeOffUserId = null;
                String writeOffUserName = null;
                if(writeOffMap.get("writeOffUserId")!=null){
                    writeOffUserId = Long.valueOf(writeOffMap.get("writeOffUserId").toString());
                    writeOffUserName = writeOffMap.get("writeOffUserName").toString();
                }
                //更新销量
                for(OrderGoods orderGoods:orderGoodsList){
                    log.info(">>minjie 更新指定谁和激活权益："+orderGoods);
                    //更新指定谁的权限
                    UpdateWrapper<OrderGoods> orderGoodsUpdateWrapper2 = new UpdateWrapper<>();
                    orderGoodsUpdateWrapper2.eq("order_goods_id",orderGoods.getOrderGoodsId());
                    OrderGoods orderGoods2 = new OrderGoods();
                    orderGoods2.setUserId(userId);
                    //激活权益：收银台不激活
                    if(orderStatus==2) {
                        orderGoods2.setRemainWriteOffTimes(orderGoods.getAmount());
                    }else {//收银插入核销表
                        List<OrderWriteOffLog> orderWriteOffLogList = new LinkedList<>();
                        for(int i=0;i<orderGoods.getAmount();i++){
                            OrderWriteOffLog orderWriteOffLog = new OrderWriteOffLog();
                            orderWriteOffLog.setOrderGoodsId(orderGoods.getOrderGoodsId());
                            if(orderr.getPayType()==1 && orderr.getCashierId()!=null){
                                orderWriteOffLog.setPayType(4);//微信收银
                            }else{
                                orderWriteOffLog.setPayType(orderr.getPayType());
                            }
                            orderWriteOffLog.setPrice(orderGoods.getGoodsPrice());
                            orderWriteOffLog.setReceiver(orderr.getReceiver()==null?nickname:orderr.getReceiver());
                            orderWriteOffLog.setReceiverHeadimgurl(orderr.getReceiverHeadimgurl()==null?headimgurl:orderr.getReceiverHeadimgurl());
                            orderWriteOffLog.setStoreId(orderr.getStoreId());
                            if(writeOffUserId!=null){
                                orderWriteOffLog.setUserId(writeOffUserId);
                                orderWriteOffLog.setUserName(writeOffUserName);
                            }else {
                                orderWriteOffLog.setUserId(orderr.getCashierId());
                                orderWriteOffLog.setUserName(orderr.getCashierName());
                            }
                            orderWriteOffLog.setOrderId(orderr.getOrderId());
                            orderWriteOffLogList.add(orderWriteOffLog);
                        }
                        //插入核销表
                        orderWriteOffLogService.saveBatch(orderWriteOffLogList);
                    }
                    orderGoodsService.update(orderGoods2,orderGoodsUpdateWrapper2);
                    goodsSpecificationServiceClient.updateSalesVolume(orderGoods.getGoodsSpecificationId(),orderGoods.getAmount());
                }
            }
            if(orderStatus==4) {
                //更新订单统计
                orderStats2Service.createOrUpdate(orderr, 0, 1);
                //分销费用
                int shareAmount = 0;
                //门店获得资金
                int amount = orderr.getPrice();
                //手续费=订单总金额*6/1000;
                int fees = orderr.getPrice()*6/1000;
                ResultBody<RetailOrder> retailOrderResultBody = retailOrderServiceClient.getRetailOrder(orderr.getOrderId());
                if(retailOrderResultBody!=null && retailOrderResultBody.getCode() == ResultEnum.OK.getCode()){
                    RetailOrder retailOrder = retailOrderResultBody.getData();
                    if(retailOrder!=null){
                        shareAmount = retailOrder.getProfit()==null?0:retailOrder.getProfit();
                        int price = orderr.getPrice()==null?0:retailOrder.getProfit();
                        int profit = retailOrder.getProfit()==null?0:retailOrder.getProfit();
                        amount = price - profit;
                    }
                }
                log.info(">> minjie 核算后的门店资金：{}，分销费用：{}，手续费：{}",amount,shareAmount,fees);
                //处理流水
                String des = "无需核销的资金记录";
                storeFlowServiceClient.saveStoreFlow(orderr.getStoreId(),amount,shareAmount,fees,
                        1, orderr.getOrderId(),des,Integer.valueOf(DateUtils.formatYear()),
                        Integer.valueOf(DateUtils.formatMonth()),Integer.valueOf(DateUtils.formatDay()));
                //更新门店资金
                ResultBody<Store> retStrore = storeServiceClient.updateStoreBalance(orderr.getStoreId(),amount);
                if(retStrore.getCode() != ResultEnum.OK.getCode()){
                    log.info(">>minjie 更新门店资金出错,storeId:{},balance:{}",orderr.getStoreId(),orderr.getPrice());
                }
            }
            if(orderr.getPayBalances()>0){
                //加上余额明细
                mpweixinServiceClient.saveFlow(orderr.getOrderId(),userId,orderr.getPayBalances(),3);
            }
            //直接更新用户分享得到的钱
            if(orderr.getActType()!=null && orderr.getActType().equals(2)){
                retailOrderServiceClient.updateRetailOrder(orderr.getOrderId(),4);
            }
            //通知门店排号
            if(reserveOrder!=null){
                log.info(">>minjie 修改排号状态，排号id：{}",reserveOrder.getReserveId());
                //修改排号状态
                Reserve newReserve = new Reserve();
                newReserve.setReserveId(reserveOrder.getReserveId());
                newReserve.setStatus(5);
                if(reserveService.updateById(newReserve)){
                    reserveService.noticeReserve(orderr.getStoreId());
                }
            }
        }
        //远程调用云商通模块
        yunStPaymentServiceClient.payCallBack(rps);
        return ResultBodyUtils.ok();
    }

    /**
     * 查询核销人
     * @return
     */
    private Map<String,Object> getWriteInfomation(Orderr orderr, ReserveOrder reserveOrder){
        Map<String,Object> resultMap = Maps.newHashMap();
        //查询核销人
        Long writeOffUserId = null;
        String writeOffUserName = null;
        if(reserveOrder!=null){
            //查询排队单
            Reserve reserve = reserveService.getById(reserveOrder.getReserveId());
            ResultBody<StoreStaff> storeStaffResultBody = storeStaffServiceClient.selectStoreStaff(orderr.getStoreId(),reserve.getStaffId(),null);
            if(storeStaffResultBody!=null && storeStaffResultBody.getCode()==ResultEnum.OK.getCode()){
                StoreStaff storeStaff = storeStaffResultBody.getData();
                if(storeStaff!=null){
                    writeOffUserId = storeStaff.getUserId();
                    writeOffUserName = storeStaff.getName();
                }
            }
        }else if(orderr.getCashierId()==null){
            ResultBody<StoreStaff> storeStaffResultBody = storeStaffServiceClient.selectStoreStaff(orderr.getStoreId(),null,"MERCHANT");
            if(storeStaffResultBody!=null && storeStaffResultBody.getCode()==ResultEnum.OK.getCode()){
                StoreStaff storeStaff = storeStaffResultBody.getData();
                if(storeStaff!=null){
                    writeOffUserId = storeStaff.getUserId();
                    writeOffUserName = storeStaff.getName();
                }
            }
        }
        resultMap.put("writeOffUserId",writeOffUserId);
        resultMap.put("writeOffUserName",writeOffUserName);
        return resultMap;
    }

    /**
     * 查询订单是否关联预约单
     * @param orderId
     * @return
     */
    private ReserveOrder getReserveOrder(long orderId){
        QueryWrapper<ReserveOrder> reserveOrderQueryWrapper = new QueryWrapper<>();
        reserveOrderQueryWrapper.eq("order_id",orderId);
        reserveOrderQueryWrapper.orderByDesc("ct");
        reserveOrderQueryWrapper.last("LIMIT 1");
        ReserveOrder reserveOrder = reserveOrderService.getOne(reserveOrderQueryWrapper);
        return reserveOrder;
    }

    /**
     * 退款回调
     * @param rps
     * @param orderId
     * @return
     */
    @RequestMapping("refundCallBack")
    public ResultBody refundCallBack(
            @RequestParam(value = "rps") String rps,
            @RequestParam(value = "orderId") long orderId){
        log.info(">>minjie  进入退款回调---- rps:{}",rps);
        JSONObject requset = JSON.parseObject(rps);
        JSONObject returnValue = requset.getJSONObject("returnValue");
        String status =  requset.getString("status");
        return ResultBodyUtils.ok();
    }

    @RequestMapping("withdrawCallBack")
    public ResultBody withdrawCallBack(@RequestParam(value = "rps") String rps){
        log.info(">>minjie  进入提现回调---- rps:{}",rps);
        JSONObject requset = JSON.parseObject(rps);
        JSONObject returnValue = requset.getJSONObject("returnValue");
        String status =  requset.getString("status");
        if(status.equals("OK")){
            yunStPaymentServiceClient.withdrawCallBack(rps);
        }
        return ResultBodyUtils.ok();
    }

}
